﻿using B.S.Filtration.Domain;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Read.Api.Application.Command.ProcessCommand;
using B.S.Filtration.Read.Api.Dto;
using MediatR;
using SqlSugar;
using System.Net;

namespace B.S.Filtration.Read.Api.Application.CommandHander.ProcessHandler
{
    public class GetBYIdCraftProcedureCommandHandler : IRequestHandler<GetBYIdCraftProcedureCommand, APIResult<List<CraftProcedureDTO>>>
    {
        private readonly ISqlSugarClient db;

        public GetBYIdCraftProcedureCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<List<CraftProcedureDTO>>> Handle(GetBYIdCraftProcedureCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<CraftProcedureDTO>>();

                // 检查工艺ID是否有效
                if (request.CraftsmanshipId <= 0)
                {
                    result.code = APIResultCode.failed;
                    result.msg = "工艺ID参数无效";
                    return result;
                }

                // 构建查询
                var query = db.Queryable<CraftProcedure, Procedure, ProcessType>((cp, pd, pt) => new object[]
                {
                    JoinType.Inner, cp.ProcedureId == pd.ProcedureId,  // 工艺工序关系表与工序表关联
                    JoinType.Inner, pd.ProcessTypeId == pt.ProcessTypeId  // 工序表与工序类型表关联
                })
                .Where((cp, pd, pt) => cp.CraftsmanshipId == request.CraftsmanshipId)  // 筛选指定工艺ID的记录
                .Select((cp, pd, pt) => new CraftProcedureDTO
                {
                    ProcedureId = pd.ProcedureId,
                    ProcessCode = pd.ProcessCode,
                    ProcessName = pd.ProcessName,
                    leader = pd.leader,
                    Affiliation = pd.Affiliation,
                    Status = pd.Status,
                    Remark = pd.Remark,
                    ProcessTypeId = pt.ProcessTypeId,
                    TypeName = pt.TypeName,
                    // 添加关联表中的其他需要的字段
                    CraftProcedureId = cp.CraftProcedureId,  // 工艺工序关系ID
                });


                // 执行查询
                var list = await query.ToListAsync();

                // 处理查询结果
                if (list == null || list.Count == 0)
                {
                    result.code = APIResultCode.failed;
                    result.msg = "未找到相关工序数据";
                }
                else
                {
                    result.code = APIResultCode.success;
                    result.msg = "查询成功";
                    result.data = list;
                }


            return result;
        }
    }
}